package project.web;

import com.alibaba.fastjson.JSON;
import project.pojo.Department;
import project.pojo.Departments;
import project.pojo.Major;
import project.pojo.Majors;
import project.service.DepartmentService;
import project.service.MajorService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

@WebServlet("/DepartmentMajorServlet")
public class DepartmentMajorServlet extends HttpServlet {
    DepartmentService departmentService = new DepartmentService();
    MajorService majorService = new MajorService();
    String Q_DEPARTMENT = "department";
    String Q_MAJOR = "major";
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String q_string = request.getParameter("q");
        if (Q_DEPARTMENT.equals(q_string)){
            List<Department> departmentList = departmentService.selectNames();
            Departments departments = new Departments();
            departments.setDepartments(departmentList);
            String departmentsJSON = JSON.toJSONString(departments);
            response.setHeader("Content-type", "text/json;charset=UTF-8");
            response.getWriter().write(departmentsJSON);
        }else if(Q_MAJOR.equals(q_string)){
            String departmentName = request.getParameter("departmentName");

//            byte[] bytes = departmentName.getBytes(StandardCharsets.ISO_8859_1);
//            departmentName = new String(bytes, StandardCharsets.UTF_8);

            List<Major> majorList = majorService.selectMajorsByDepartmentName(departmentName);
            Majors majors = new Majors();
            majors.setMajors(majorList);
            String majorsJSON = JSON.toJSONString(majors);
            response.setHeader("Content-type", "text/json;charset=UTF-8");
            response.getWriter().write(majorsJSON);
        }

//        System.out.println(departmentsJSON);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
